import os
import os.path

"""Documentation goes here"""

class URI(object):
    def __init__(self, uri_string, uri_prefix = ''):
        self.PATH = self._conform(uri_prefix, uri_string)

    def path(self):
        return self.PATH

    def text(self):
        if(self._is_file()):
            file_handle = open(self.path(), 'r')
            text = "".join(file_handle.readlines())
            file_handle.close()
            return text
        return False

    def _tuple(self, uri_string):
        (head, tail) = os.path.split(str(uri_string))
        if(os.path.join(head) == uri_string):
            return (head,)
        else:
            return self._tuple(head) + (tail,)

    def _string(self, uri_tuple):
        return os.path.join(*uri_tuple)

    def _conform(self, head, tail):
        uri_string = ""
        if(self._exists(head + tail)):
            uri_string = head + tail
        elif(self._exists(os.path.join(head, tail))):
            uri_string = os.path.join(head, tail)
        else: # This URI does not exist
            return False

        return self._string(self._tuple(uri_string))

    def _exists(self, uri_string):
        if(os.path.exists(uri_string)):
            return True
        return False

    def _is_file(self):
        if(self.path()):
            if(os.path.isfile(self.path())):
                return True
        return False

def _find_path(uri_string, context):
    root_uri = _uri(context['cotton']['base_uri'])
    source_uri = _uri(os.path.split(context['cotton']['document_uri'])[0])

    # At this point, we know two directories: the top level web directory
    # (root_uri) and the directory that the originating document is in (source_uri).

    uri_options = [source_uri, root_uri, '',]

    if(os.path.isabs(uri_string)):
        # try the root uri first
        uri_options = [root_uri,] + uri_options

    for option in uri_options:
        uri = _get_uri(uri_string, option)
        if(uri):
            return uri

    return False
